import SearchFilter from "./components/filter.vue";
import PropDialog from './components/prop-dialog.vue';
import MsgsDialog from "./components/msgs-dialog.vue";
import UpdateDialog from "./components/update-dialog.vue";
import QuestionShow from '@rc/pages/components/question-base/question-show/index.vue';
import questionApi  from "@rc/apis/rc/question.mjs";
import RepeatProcessSingleDialog from "@rc/pages/questions/components/edit-frame/components/repeat-process-single-dialog.vue";

export default {
    name: 'question-list',
    components:{
        SearchFilter,
        PropDialog,
        MsgsDialog,
        UpdateDialog,
        QuestionShow,
        RepeatProcessSingleDialog,
    },
    data() {
        return {
            listType:'all',//默认为全部试题 //全部试题all 待审核audit 审核失败fail
            tableHeight:300,
            isShowTableLoading:false,//列表查询加载中
            isShowAnswer:false,//是否勾选答案与解析
            orderKey:'rq.create_time',//默认按照添加时间排序
            content:'',//题干内容
            contentKey:'questionTitle', //题干搜索字段
            page: {
                pageIndex: 1,
                pageSize: 10,
                pageCount: 0
            },
            questionList:[],//试题列表原数据
            showQuestionList:[],//显示数据
            propDialogMsg:{// 自定义列表弹窗信息
                show:false
            },
            updateDialogMsg:{//批量修改弹窗信息
                show:false,
                projectId:'',
                subjectId:''
            },
            questionType:['A','CF','L','C'],//组合题型
            //自定义列
            checkedPropList:[],
            propList:[],//所有可自定义列表
            columns:{ //每一列的配置项   隐藏小题的审核状态、审核人和修改时间、修改人
                questionDeveloperName:{},
                createUserName:{},
                updateUserName:{
                    subNotShow:true
                },
                checkUserName:{
                    subNotShow:true
                },
                auditStatus:{
                    status:{
                        P:'待审核',
                        Y:'审核通过',
                        N:'审核不通过'
                    },
                    subNotShow:true
                },
                isAvailable:{
                    label:'启用状态',
                    status: {
                        Y:'启用',
                        N:'禁用'
                    }
                },
                createTime:{},
                updateTime:{
                    subNotShow:true
                },
                checkTime:{
                    subNotShow:true
                }
            },
            //批量操作
            isShowBatchLoading:false,
            isAllCheck:false,
            selectItems:[],
            timer:null, //防抖使用的定时器
            isShowProcessDialog: false,
            processQuestionResourceId: null,
            processRepeatResourceId: undefined,
            processQuestion: null,
            opOrigin: '启用',
            opText: '',
            willShow: '',
            willHide: '',
        };
    },
    computed:{
        sortPropArr(){
            let propArr =  [
                {
                    key:'rq.create_time',
                    text:'添加时间'
                },
                {
                    key:'rq.update_time',
                    text:'修改时间'
                },

            ];
            if(this.listType!=='audit') {
                propArr.push({
                    key:'rq.check_time',
                    text:'审核时间'
                });
            }
            return propArr;
        },
        // 当前选中的表格id集合
        selectIds() {
            return this.selectItems.map((i) => i.resourceId);
        },
        //选择的资源是否可以进行批量修改
        isCanUpdate() {
            if (!this.selectItems.length) {
				return false;
			}
            const  {projectId,subjectId} = this.selectItems[0];
            const isContinue = this.selectItems.every((item)=> item.projectId===projectId && item.subjectId===subjectId && projectId&& subjectId );
            return isContinue;
        }
    },
    watch:{
        isShowAnswer:{
            handler(val){
                this.showQuestionList.forEach(item=>{
                    item.isAnalysis = val;
                });
            }
        },
        checkedPropList:{
            deep:true,
            handler(){
                this.showQuestionList = JSON.parse(JSON.stringify(this.showQuestionList));
                this.$nextTick(() => {
                    this.$refs['tableRef'].doLayout();
                });
            }
        }
    },
    created() {
        nlapp.PermissUtil.checkPagePermiss("rc/questions/list-list");
        this.queryQuestionUserCustomList();
    },
    mounted() {
        this.page.pageSize = 10;
        this.onSubmit();
    },
    activated() {
        this.$refs['tableRef'].doLayout();
        this.debounce(this.onSearch,1000);
    },
    methods: {
        //隐藏自定义属性展示
        hiddenProp(prop){
            //待审核页面 -审核时间和审核人不展示
            if(this.listType==='audit' && ['checkUserName','checkTime'].includes(prop.field)){
                return true;
            }
            return false;
        },
        //处理自定义列的内容逻辑
        getPropValue(row,prop) {
            if(row.parentResourceId &&  this.columns[prop.field].subNotShow){//小题不显示
                return '';
            }
            return this.columns[prop.field].status? this.columns[prop.field].status[row[prop.field]]:row[prop.field] ;
        },
        onSubmit(){
            this.page = {
                pageIndex: 1,
                pageSize: this.page.pageSize,
                pageCount: 0
            };
            this.debounce(this.onSearch,1000);
        },
        //重置时，除了表单筛选项,另外要求清空题干内容和资源id
        onReset(){
           this.content = '';
           this.onSubmit();
        },
        /**
         * 切换全部试题和待审核
         */
        onChangeListType(){
            this.page = {
                pageIndex: 1,
                pageSize: this.page.pageSize,
                pageCount: 0
            };
            this.onSearch();
        },
        /**
         * 切换排序类型
         */
        onChangeSort(orderKey){
           if(this.orderKey === orderKey){
             return;
           }
           this.orderKey = orderKey;
           this.onSubmit();
        },
        //函数防抖
        debounce(func, wait=0) {
            if (!this.timer) {
                func.apply(this);
                this.timer = setTimeout(() => {
                    clearTimeout(this.timer);
                    this.timer = null;
                }, wait);
            }
        },
        /**
         * 搜索
         */
        onSearch(){
            this.isShowTableLoading=true;
            const params = this.$refs.searchFilter.api_result();
            params[this.contentKey] = this.content;
            params.orderKey = this.orderKey;
            params.orderVal = 'N';//倒序排序
            this.questionList = [];
            this.showQuestionList = [];

            if(this.listType==='audit') { //待审核
                params.auditStatus='P';
                if(this.orderKey==='rq.check_time'){
                    this.orderKey='rq.create_time';
                }
            }
            if(this.listType==='fail') { //审核不通过
                params.auditStatus='N';
            }
            this.selectItems = [];
            questionApi.queryQuestionAllList({
                data: {
                    pageIndex: PageUtil.getStartIndex(this.page),
                    pageSize: this.page.pageSize,
                    ...params
                },
                success: (result) => {
                    this.$nextTick(() => {
                        if (Array.isArray(result.data) && result.data.length) {
                            this.$refs['tableRef'].doLayout();
                        }
                    });
                    this.isAllCheck = false;
                    const questionList  = result.data;
                    let showQuestionList = [];

                    questionList.forEach((item,index)=>{
                        showQuestionList.push({
                            ...item,
                            qIndex:index+1,
                            isAnalysis:this.isShowAnswer,
                            smallQuestionList:[]
                        });

                        if(item.smallQuestionList ){ //组合题 将子题插入到大题后
                            item.smallQuestionList.forEach((sq,sqIndex)=>{
                                let isSqLast= sqIndex === item.smallQuestionList.length-1;//是不是最后一道小题
                                showQuestionList.push({
                                    ...sq,
                                    parentType:item.questionType,//大题类型
                                    parentResourceId:item.resourceId,//大题标识
                                    qIndex:(index+1)+'.'+(sqIndex+1),//列表上显示的序号
                                    isSqLast,//是否是最后一道小题
                                    isChecked:false,
                                    isAnalysis:this.isShowAnswer//是否展开解析和答案
                                });
                            });

                        }

                    });
                    this.showQuestionList = showQuestionList;
                    //列表查询到的原始数据，供分页使用
                    this.questionList = questionList;
                    this.page.pageCount = result.count;
                },
                fail:()=>{
                    this.page.pageCount = 0;
                },
                complete:(()=>{
                    this.isShowTableLoading = false;
                })
            });

        },
        // 控制表格列的边框样式
        tableCellStyle({row,columnIndex}){
             //组合题不显示前几列不显示下边框
             const cond1 = row.parentResourceId && !row.isSqLast;//小题且不是最后一道小题
             const cond2 = this.questionType.includes(row.questionType);//是组合题型
             const cond3 = (columnIndex==0 || columnIndex==1 || columnIndex==2);//选择框,序号,资源ID
             let result = { };
             if((cond2 || cond1) && cond3){
                result['border-bottom'] = 'none';
             }
             result['background'] = 'transparent';
             return result;
        },
        //控制行的背景颜色
        tableRowStyle({row}) {
            let result = { };
            let index = 0;
            //子题与大题背景颜色相同
            if(row.parentResourceId){
               index = this.questionList.findIndex(q=>q.resourceId === row.parentResourceId);
            } else {
                index = this.questionList.findIndex(q=>q.resourceId === row.resourceId);
            }
            if((index+1)%2 === 1) {
                result['background'] = '#fff';
            } else {
                result['background'] = '#FAFAFA';
            }
            //设置选中的背景颜色 小题背景颜色也发生改变
            if(this.selectIds.includes(row.resourceId) || (row.parentResourceId && this.selectIds.includes(row.parentResourceId))){
                result['background'] = '#F5F7FA';
            }
            return result;
        },
        //获取用户自定义列表
        queryQuestionUserCustomList(callback) {
            questionApi.queryQuestionUserCustomList({
				success: (data) => {

                    this.checkedPropList = data.filter(fieldItem => fieldItem.isDefault === 'Y');
                    this.propList = data;
                    callback && callback();
        	    }
            });
        },
        /**
         *点击自定义列表
         */
        onShowPropDialog(){
            this.propDialogMsg = {
                show: true
            };
        },
        onCancelPropDialog(){
            this.propDialogMsg = {
                show: false
            };
        },
        //修改用户自定义列成功
        onSuccessPropDialog(){
            this.queryQuestionUserCustomList(()=>{
                this.onCancelPropDialog();

            });
        },
        // 表格全选改变
		handleCheckAllChange(isAllCheck) {
            if(isAllCheck){
                this.selectItems = this.showQuestionList.filter(item=>!item.parentResourceId);
            }else{
                this.selectItems = [];
            }
            this.showQuestionList.forEach((item)=>{
                item.isChecked = isAllCheck;
            });
            this.showQuestionList = JSON.parse(JSON.stringify(this.showQuestionList));
		},
        //表格内选择项变化
        rowSelectionChange(row){
            if(row.isChecked === false){
                let index = this.selectItems.findIndex (item=>item.resourceId === row.resourceId);
                if(index!==-1) {
                    this.selectItems.splice(index,1);
                }
            } else {
                this.selectItems.push(row);
            }
            this.isAllCheck = this.showQuestionList.filter(item=>!item.parentResourceId).length === this.selectItems.length;
        },
        //批量审核
        auditQuestion(resourceId=''){
            if (!resourceId && !this.selectIds.length) {
				this.$message.warning("请先选择试题!");
				return;
			}
            this.$confirm('请选择审核结果', '试题审核', {
                distinguishCancelAndClose: true,
                confirmButtonText:'通过',
                cancelButtonText:'不通过',
                type: 'warning'
            }).then(() => {
                this.updateBatchQuestionAuditStatus(resourceId,'Y');
            }).catch(action => {
                if(action === 'cancel'){
                    this.updateBatchQuestionAuditStatus(resourceId,'N');
                }
            });
        },
        //执行审核操作
        updateBatchQuestionAuditStatus(resourceId,checkStatus){
            if(!resourceId){
                this.isShowBatchLoading = true;
            }
            const resourceIds = resourceId? [resourceId]:this.selectIds;
            questionApi.updateBatchQuestionAuditStatus({
                    data: {
                        resourceIds,
                        checkStatus
                    },
                    success: () => {
                    this.$message.success('试题审核完成');
                    if(this.listType==='audit' || this.listType==='fail') { //待审核
                        this.onSearch();
                    }else{
                        this.queryQuestionBaseMessage(resourceIds);//局部刷新试题
                    }

                },
                complete: () => {
                    if(!resourceId){
                        this.isShowBatchLoading = false;
                    }

                }
            });
        },
        /**
         * 批量启用禁用
         * @param {string} type 启用或禁用
         * @param {object} [resource] 单个试题启用禁用传递此参数
         */
        shelveQuestion(type, resource, isSmall = false) {
            if (!resource && !this.selectIds.length) {
				this.$message.warning("请先选择试题!");
				return;
			}
            const messageObj = {
                'shelve-n':{
                    msg:'确定要禁用试题吗？（同时禁用试卷中关联的试题）',
                    status:'N'
                },
                'shelve-y':{
                    msg:'确定要启用试题吗？（同时启用试卷中关联的试题）?',
                    status:'Y'
                },
            };
            let params = {
                isAvailable:messageObj[type].status
            };
            let url = '';
            if(resource){
                params.resourceId = resource.resourceId;
                url='updateQuestionAvailable';
            }else{
                params.resourceIds =  this.selectIds;
                url='updateBatchQuestionAvailable';
            }
            this.$confirm(messageObj[type].msg, '提示', {
                confirmButtonText:'确定',
                cancelButtonText:'取消',
                type: 'warning'
            }).then(() => {
                if(params.resourceIds){
                    this.isShowBatchLoading = true;
                }
                questionApi[url]({
                    data: {
                       ...params
                    },
                    success: ({ operatedResourceId, repeatResourceId, repeatNum, result }) => {
                        console.warn('shelveQuestion', operatedResourceId, repeatResourceId, repeatNum, resource);
                        if (repeatResourceId) {
                            if (isSmall && type === 'shelve-n') {
                                this.opText = '禁用子题后试题';
                            } else {
                                this.opText = '';
                                this.opOrigin = type === 'shelve-n' ? '禁用' : '启用';
                            }
                            
                            if (type === 'shelve-n' && isSmall) {
                                this.willHide = resource.resourceId;
                                this.willShow = '';
                            } else if (type === 'shelve-y' && isSmall) {
                                this.willHide = '';
                                this.willShow = resource.resourceId;
                            } else if (type === 'shelve-n') {
                                this.willHide = this.showQuestionList.filter(({ parentResourceId }) => resource.resourceId === parentResourceId).map(({ resourceId }) => resourceId).join();
                                this.willShow = '';
                            } else if (type === 'shelve-y') {
                                this.willHide = '';
                                this.willShow = this.showQuestionList.filter(({ parentResourceId }) => resource.resourceId === parentResourceId).map(({ resourceId }) => resourceId).join();
                            } else {
                                this.willHide = '';
                                this.willShow = '';
                            }
                            this.isShowProcessDialog = true;
                            this.processQuestionResourceId = operatedResourceId;
                            this.processRepeatResourceId = repeatResourceId;
                            return;
                        } else if (repeatNum > 0) {
                            return this.$alert(`${repeatNum}道试题启用失败：系统中已存在启用状态的内容相同的重复试题`, '试题重复提示', {
                                confirmButtonText: '我知道了',
                            }).then(() => {
                                if (result) {
                                    this.queryQuestionBaseMessage(params.resourceIds);
                                }
                            }).catch(() => {});
                        }
                        const message = params.isAvailable==='Y'?'试题已启用':"试题已禁用";
                        this.$message.success(message);
                        let resourceIds=[];
                        if(resource){//单个处理时,当是小题时，传递大题的resourceId;
                            resourceIds = resource.parentResourceId?[resource.parentResourceId]:[resource.resourceId];
                        } else {
                            resourceIds =  params.resourceIds;
                        }
                        this.queryQuestionBaseMessage(resourceIds);//局部刷新试题
                    },
                    complete: () => {
                        if (params.resourceIds) {
                            this.isShowBatchLoading = false;
                        }
                    }
                });
            });


        },
        /**
         * 启用禁用/审核后局部 刷新页面
         * @param {*} type 启用禁用还是审核
         * @param {*} resourceIds
         */
         queryQuestionBaseMessage(resourceIds){
            //修改单个题的审核启用状态
            const  changeStatus = (question)=>{
                let index = this.showQuestionList.findIndex((q)=>question.resourceId===q.resourceId);
                if(index!==-1){
                    let currentQuestion = this.showQuestionList[index];
                    currentQuestion.isAvailable = question.isAvailable;
                    currentQuestion.auditStatus = question.auditStatus;
                    currentQuestion.createUserName = question.createUserName;
                    currentQuestion.updateUserName = question.updateUserName;
                    currentQuestion.createTime = question.createTime;
                    currentQuestion.updateTime = question.updateTime;
                    currentQuestion.checkTime = question.checkTime;
                    currentQuestion.checkUserName = question.checkUserName;
                    currentQuestion.questionDeveloperName = question.questionDeveloperName;
                    this.$set(this.showQuestionList,index,currentQuestion);
                }
            };
            questionApi.queryQuestionBaseMessage({
                data: {
                    resourceIds
                },
                success: (data) => {
                    data.forEach((question)=>{
                        changeStatus(question);
                        if(question.smallQuestionList ){ //组合题 将子题插入到大题后
                            question.smallQuestionList.forEach((sq)=>{
                                changeStatus(sq);
                            });
                        }
                    });
                }
            });
        },
        // 删除
        deleteQuestion(resourceId, isSmall = false){
            if (!resourceId && !this.selectIds.length) {
				this.$message.warning("请先选择试题!");
				return;
			}
            this.$confirm('确定要删除试题吗？（同时删除试卷中关联的试题），此操作不可恢复。', '提示', {
                confirmButtonText:'确定',
                cancelButtonText:'取消',
                type: 'warning'
            }).then(() => {
                if(!resourceId){
                    this.isShowBatchLoading = true;
                }

                questionApi.deleteBatchQuestion({
                    data: {
                        resourceIds: resourceId ? [resourceId] : this.selectIds,
                    },
                    success: ({ operatedResourceId, repeatResourceId, repeatNum }) => {
                        console.warn('shelveQuestion', operatedResourceId, repeatResourceId, repeatNum );
                        if (repeatResourceId) {
                            if (isSmall) {
                                this.opText = '删除子题后试题';
                            } else {
                                this.opText = '';
                                this.opOrigin = '删除';
                            }
                            if (isSmall) {
                                this.willHide = resourceId;
                                this.willShow = '';
                            } else {
                                this.willHide = this.showQuestionList.filter(({ parentResourceId }) => resourceId === parentResourceId).map(({ resourceId }) => resourceId).join();;
                                this.willShow = '';
                            }

                            this.isShowProcessDialog = true;
                            this.processQuestionResourceId = operatedResourceId;
                            this.processRepeatResourceId = repeatResourceId;
                            return;
                        } else if (repeatNum > 0) {
                            return this.$alert(`${repeatNum}道试题启用失败：系统中已存在启用状态的内容相同的重复试题`, '试题重复提示', {
                                confirmButtonText: '我知道了',
                            }).catch(() => {});
                        }
                        this.$message.success('试题已删除');
                        this.onSearch();
                    },
                    complete: () => {
                        if (!resourceId) {
                            this.isShowBatchLoading = false;
                        }
                    },
                });

            });

        },
        //跳转到添加试题界面
        onGoToAddPage(){
            nlapp.PageUtil.navigateToOnly('/rc/questions/add');
        },
        /**
         * 跳转到编辑试题界面
         * @param {string} resourceId 试题id
         * @param {string} questionType 试题类型
         * @param {string} parentResourceId 试题为小题时，大题id
         * @param {string} parentType 试题为小题时，大题类型
         */
        onGoToEditPage({resourceId,questionType,parentResourceId,parentType}){
            let resourceIds = [];
            if(parentResourceId){ //小题，取大题下所有的小题
                let showQuestionList = this.showQuestionList.filter(question=>question.parentResourceId ===parentResourceId);
                resourceIds = showQuestionList.map(question=>question.resourceId);
            }else{ //取整个列表的资源id
                resourceIds = this.questionList.map(question=>question.resourceId);
            }
            nlapp.PageUtil.navigateToOnly('/rc/questions/edit', {
                resourceId,
                questionType,
                parentResourceId,
                parentType
            });
            Storage.set('rc-editIds',resourceIds);
        },
        // 批量修改
        onBatchUpdate(){
            if (!this.selectItems.length) {
                this.$message.warning("请选择试题资源!");
				return;
			}
            const  {projectId,subjectId,projectName,subjectName} = this.selectItems[0];
            const isContinue = this.selectItems.every((item)=> item.projectId===projectId && item.subjectId===subjectId && projectId&& subjectId );
            if(!isContinue){
                this.$message.warning("只能批量修改同一科目试题!");
                return;
            }

            this.updateDialogMsg = {
                show: true,
                projectId,
                subjectId,
                projectName,
                subjectName
            };
        },
        /**
         * 批量修改成功回调
         */
        onSuccessUpdateDialog(){
            this.onCancelUpdateDialog();
            this.onSubmit();
        },
        /**
         * 关闭批量修改弹窗
         */
        onCancelUpdateDialog(){
            this.updateDialogMsg = {
                show: false
            };
        },
        /**
         * 显示详细信息
         */
        openMsg(resourceId,type) {
            this.$refs.msgsDialog.open(resourceId,type);
        }

    }
};
